<?php

namespace catchAdmin\api\controller;

use catcher\Code;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;
use think\Request;
/*
 * 运单接口
 * */
class Logistics extends Index
{
    /**
     * 获取token
     * @param Request $request
     * @return string
     */
    public function logisticsService(Request $request)
    {

        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post();
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('logistics',json_encode($data,JSON_UNESCAPED_UNICODE));

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token

            //方法分发
            switch ($serviceType)
            {
                //中外运回执
                case 'zwyWaybillReceipt':
                    $result = $this->zwyWaybillReceipt($data);
                    break;

                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn('logistics',$result);

        } catch (\Exception $exception) {
            return $this->commonReturn('logistics',['code'=>Code::FAILED, 'msg'=>$exception->getMessage()]);

        }

    }
    /**
     * 中外运订单回执
     * @param  $data
     * @return array
     */
    protected function zwyWaybillReceipt($data)
    {
        $keys = ['orderNo','returnStatus','receiptType','lgWbNo'];
        $value = $this->check_fields($data, $keys, false);//验证字段
        //判断参数
        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }


        try {
            if($value['receiptType'] === 'ewb'){
                $params['waybill_status'] = $value['returnStatus'];
                $params['modifyTime'] = date('Y-m-d H:i:s');

                if(array_key_exists('lgWbNo', $value)){
                    $params['bill_no'] = $value['lgWbNo'];
                }
                $res = Db::table('db_customs_order')
                    ->field('id')
                    ->where('orderId', $value['orderNo'])
                    ->find();
                if(!$res){
                    return [ 'code'=>Code::FAILED , 'msg'=> '订单号不存在'];
                }

                $res = Db::table('db_customs_order')
                    ->where('orderId', $value['orderNo'])
                    ->save($params);
                if($res){
                    return [ 'code'=> Code::SUCCESS , 'msg'=> '回执处理成功', 'data'=>[]];
                }else{
                    return [ 'code'=>Code::FAILED , 'msg'=> '回执处理失败'];
                }
            }else{
                return [ 'code'=>Code::FAILED , 'msg'=> '无约定的receiptType类型'];
            }

        } catch (\Exception $e) {

            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }
}